/*!
 * OpenSocial jQuery Event Tracking 0.1.2
 * http://code.google.com/p/opensocial-jquery/
 *
 * Copyright(C) 2009 Nakajiman Software Inc.
 * http://nakajiman.lrlab.to/
 *
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 */
(function() { 

// Register Application
var registerApp = function() {
  
  jQuery('<a href="http://opensocialhost.com/"/>')
	.text('Oops, this application was unauthorized. Register here.')
	.click(function() {

      var appKey = prompt('Enter application key of OpenSocial Host:');
	  if (appKey !== null) {
		
		var url = 'http://opensocialhost.com/app/register';  
	    var data = { application_key: appKey };
	    
		jQuery.ajax({
          type: 'post', url: url, oauth: 'signed', data: data, dataType: 'json'
        }).next(function(r) {
          if (r.hadError)
		    throw r.errorCode;
		  alert('Thanks, this application has been registered. Reload this page.');
	    }).error(function(e) {
		  alert('Oops, there was a problem: '+e);
	    });
	  }
      
	  return false;
    
	})
	.minimessage();

};

// Track Queue
var tracks = [];

// Track
var track = function(type, data, fn) {
  
  tracks.push({ type: type, data: data,	t: new Date().getTime() });

  if (tracks.length >= 10 || fn) {
  
    var url = 'http://opensocialhost.com/data/insert';
	var data = {}, i = 1;

    $.each(tracks, function(k, v) {
      data['key'+i] = [ v.type, v.t, Math.random() ].join(':');
      data['value'+i] = gadgets.json.stringify(v.data);
      i++; 
    });

	tracks.length = 0; // Empty

    data.read_permission = 'private';
    data.write_permission = 'private';

    jQuery.ajax({
      type: 'post',
	  url: url,
	  oauth: 'signed',
	  data: data,
	  dataType: 'json',
	  global: false // Disable global event
    }).next(function(r) {
      if (r.hadError && r.errorCode == 'UNAUTHORIZED')
	    registerApp(jQuery.untrack()); // stop
      if (fn) fn();
    });

  }
};

// Track Click
var trackClick = function(target, event) {
  
  var target = jQuery(target);
  
  track('click', {
	label: target.attr('title') || target.text(),
	value: target.attr('href') || '',
	x: event.pageX,
	y: event.pageY
  });

};

jQuery.extend({

// Track
track: function() {

  // ready
  jQuery(document).ready(function($, data) {
    track('ready', { name: jQuery.view(), data: data });
  });

  // a.click
  jQuery('a').live('click.track', function(event) {
    trackClick(this, event);
  });

  // ajax
  jQuery(document).ajaxSend(function(event, xhr, data) {
    track('ajax', { type: data.type, url: data.url });
  });

  // view
  jQuery.view = function(name, data) {
    if (name === undefined)
	  return _view(name, data);
	track('view', { name: name, data: data || {} }, function() {
      _view(name, data);
	});
  };

},

// Un Track
untrack: function() {

  // a.click
  jQuery('a').die('click.track');

  // ajax TODO: namespace or fn
  jQuery(document).unbind('ajaxSend');

  // view
  jQuery.view = _view;

}

});

// Keep a copy of the old view
var _view = jQuery.view;

})();
